﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.Utility;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Medical.Utility;
using Sector7.Medical.EntityType;
using System.IO;
using Sector7.Framework.EntityType;
using System.Reflection;
using Microsoft.Win32;
using System.Security.Cryptography;
using Sector7.Medical.TRAS;

namespace Sector7.Medical.INFM.Controls
{
    /// <summary>
    /// EmployeeSummaryControl.xaml 的交互逻辑
    /// </summary>
    public partial class EmployeeSummaryControl : AddModeControlBase
    {
        #region Accessor

        /// <summary>
        /// 员工信息
        /// </summary>
        private M7_Employee Employee
        {
            get { return m_entity as M7_Employee; }
            set { m_entity = value; }
        }
        #endregion

        #region Public functions
        #endregion

        #region Private functions

        /// <summary>
        /// InitCombobox
        /// </summary>
        private void InitYesNoCombobox(ComboBox combobox)
        {
            ComboBoxItem yesItem = new ComboBoxItem();
            yesItem.Content = "是";
            yesItem.Tag = true;

            ComboBoxItem noItem = new ComboBoxItem();
            noItem.Content = "否";
            noItem.Tag = false;

            List<ComboBoxItem> list = new List<ComboBoxItem>();
            list.Add(yesItem);
            list.Add(noItem);
            ClientUtil.LoadItemsSource(combobox, list);
        }

        /// <summary>
        /// InitCombobox
        /// </summary>
        private void InitYesNoCombobox()
        {
            InitYesNoCombobox(cbbIsDoctor);
            InitYesNoCombobox(cbbIsNurse);
            InitYesNoCombobox(cbbIsSpecialist);
        }

        /// <summary>
        /// Control Loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EmployeeSummaryControl_Loaded(object sender, RoutedEventArgs e)
        {
            InitYesNoCombobox();

            m_crud = CrudType.Unknown;

            Senvironments.ProgressWindow.Visibility = Visibility.Visible;

            SwitchPropertiyGroupsEnabledState(false);
            SwitchPropertiyActionButtonsState(CrudType.Unknown);
            SwitchActionButtonsState(false);

            var worker = BackgroundWorkerUtil.GetWorker(this);
            worker.DoWork += new System.ComponentModel.DoWorkEventHandler(LoadData_DoWork);
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// 加载数据工作线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadData_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            GetData();

            this.Dispatcher.BeginInvoke(new DelegateWithNothing(LoadData));
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private new void GetData()
        {
            m_empList = Agent_INFS.GetEmployeeList();
            m_groupList = Agent_INFS.GetEmployeeGroupList();
            m_deptList = Agent_INFS.GetDepartmentList(C_DepartmentFlags.SUB_DEPARTMENT);
            m_areaList = Agent_INFS.GetSickAreaList();
            m_dutyList = Agent_INFS.GetDutyList();
            m_competenceList = Agent_INFS.GetCompetenceList();
            m_genderList = Agent_INFS.GetGenderList();
            m_identityTypeList = Agent_INFS.GetIdentityTypeList();

            foreach (M7_Employee emp in m_empList)
            {
                emp.EmpGroup = m_groupList.Find(delegate(M7_EmployeeGroup __group)
                {
                    return __group.EmpGroupId == emp.EmpGroupId;
                });
                emp.Department = m_deptList.Find(delegate(M7_Department __department)
                {
                    return __department.DeptId == emp.DeptId;
                });
                emp.SickArea = m_areaList.Find(delegate(M7_SickArea __sickArea)
                {
                    return __sickArea.AreaId == emp.AreaId;
                });
                emp.Duty = m_dutyList.Find(delegate(M7_Duty __duty)
                {
                    return __duty.DutyId == emp.DutyId;
                });
                emp.Competence = m_competenceList.Find(delegate(M7_Competence __competence)
                {
                    return __competence.CompetenceId == emp.CompetenceId;
                });
                emp.Gender = m_genderList.Find(delegate(M7_Gender __gender)
                {
                    return __gender.GenderId == emp.GenderId;
                });
                emp.IdentityType = m_identityTypeList.Find(delegate(M7_IdentityType __identityType)
                {
                    return __identityType.IdentityTypeId == emp.IdentityTypeId;
                });
            }

            m_tempEmpList.AddRange(m_empList.ToArray());
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            ClientUtil.LoadItemsSource(cbbGroup, m_groupList);
            ClientUtil.LoadItemsSource(cbbDept, m_deptList);
            ClientUtil.LoadItemsSource(cbbArea, m_areaList);
            ClientUtil.LoadItemsSource(cbbDuty, m_dutyList);
            ClientUtil.LoadItemsSource(cbbComp, m_competenceList);
            ClientUtil.LoadItemsSource(cbbGender, m_genderList);
            ClientUtil.LoadItemsSource(cbbIdentityType, m_identityTypeList);
            ClientUtil.LoadItemsSource(dtgMain, m_empList);

            SwitchPropertiyActionButtonsStateByDataCount();

            Senvironments.ProgressWindow.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 清空界面输入信息
        /// </summary>
        private void ClearDepartmentPropertiye()
        {
            this.txbEmpId.Text = "";
            this.txbEmpName.Text = "";
            this.txbSpellCode.Text = "";
            this.txbSystemName.Text = "";
            this.txbPassword.Password = "";
            this.txbTelephone.Text = "";
            this.txbMobilePhone.Text = "";
            this.txbIdentity.Text = "";
            this.txbAddress.Text = "";
            this.m_photoPath = "";
            SetImage(Senvironments.BaseDirectory + DEFAULT_PHOTO_PATH);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isEnabled"></param>
        private void SwitchPropertiyGroupsEnabledState(bool isEnabled)
        {
            this.txbEmpId.IsEnabled = false;
            this.txbEmpName.IsEnabled = isEnabled;
            this.txbSpellCode.IsEnabled = isEnabled;
            this.txbSystemName.IsEnabled = isEnabled;
            this.txbPassword.IsEnabled = isEnabled;
            this.txbTelephone.IsEnabled = isEnabled;
            this.txbMobilePhone.IsEnabled = isEnabled;
            this.txbIdentity.IsEnabled = isEnabled;
            this.txbAddress.IsEnabled = isEnabled;

            this.cbbDept.IsEnabled = isEnabled;
            this.cbbArea.IsEnabled = isEnabled;
            this.cbbGroup.IsEnabled = isEnabled;
            this.cbbDuty.IsEnabled = isEnabled;
            this.cbbComp.IsEnabled = isEnabled;
            this.cbbGender.IsEnabled = isEnabled;
            this.cbbIsSpecialist.IsEnabled = isEnabled;
            this.cbbIsNurse.IsEnabled = isEnabled;
            this.cbbIsDoctor.IsEnabled = isEnabled;
            this.cbbIdentityType.IsEnabled = isEnabled;
            this.dtpBirthday.IsEnabled = isEnabled;

            this.btnBrowse.IsEnabled = isEnabled;
            this.btnResetImage.IsEnabled = isEnabled;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="crud"></param>
        private void SwitchPropertiyActionButtonsState(CrudType crud)
        {
            switch (crud)
            {
                case CrudType.Create:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
                case CrudType.Read:
                    btnAdd.IsEnabled = true;
                    btnModify.IsEnabled = true;
                    btnDelete.IsEnabled = true;
                    break;
                default:
                    btnAdd.IsEnabled = false;
                    btnModify.IsEnabled = false;
                    btnDelete.IsEnabled = false;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isVisibility"></param>
        private void SwitchActionButtonsState(bool isVisibility)
        {
            Visibility visibility = isVisibility ? Visibility.Visible : Visibility.Hidden;
            btnOk.Visibility = visibility;
            btnCancel.Visibility = visibility;

            btnAdd.IsEnabled = !isVisibility;
            btnModify.IsEnabled = !isVisibility;
            btnDelete.IsEnabled = !isVisibility;
        }

        /// <summary>
        /// 
        /// </summary>
        private void SwitchPropertiyActionButtonsStateByDataCount()
        {
            if (m_empList.Count == 0)
            {
                SwitchPropertiyActionButtonsState(CrudType.Create);
                ClearDepartmentPropertiye();
            }
            else
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);
            }
        }

        /// <summary>
        /// 生成拼音码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSpellCode_Click(object sender, RoutedEventArgs e)
        {
            txbSpellCode.Text = CharacterUtil.GetSpellCodeString(this.txbEmpName.Text.Trim());
        }

        /// <summary>
        /// 生成用户名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSystemName_Click(object sender, RoutedEventArgs e)
        {
            string userName = txbEmpName.Text.Trim();
            if (string.IsNullOrEmpty(userName))
            {
                txbSystemName.Text = "";
            }
            else
            {
                txbSystemName.Text = Agent_SYSS.GetUsername(userName);
            }
        }

        /// <summary>
        /// 操作成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EmployeeSummaryControl_AddSuccess(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 数据表选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtgMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Employee)
            {
                SwitchPropertiyActionButtonsState(CrudType.Read);

                M7_Employee employee = dtgMain.SelectedItem as M7_Employee;
                ShowEmployeeInfor(employee);
            }
            else
            {
                SwitchPropertiyGroupsEnabledState(false);
                SwitchActionButtonsState(false);
                SwitchPropertiyActionButtonsStateByDataCount();
                ClearDepartmentPropertiye();
            }
        }

        /// <summary>
        /// 显示EmployeeInfor
        /// </summary>
        /// <param name="employee"></param>
        private void ShowEmployeeInfor(M7_Employee employee)
        {
            this.txbEmpId.Text = employee.EmpId.ToString();
            this.txbEmpName.Text = employee.FullName;
            this.txbSpellCode.Text = employee.SpellCode;
            this.txbSystemName.Text = employee.Username;
            this.txbTelephone.Text = employee.Telephone;
            this.txbMobilePhone.Text = employee.Mobilephone;
            this.txbIdentity.Text = employee.IdentityId;
            this.txbAddress.Text = employee.CurrentAddr;
            this.dtpBirthday.SelectedDate = employee.Birthday;
            //this.m_photoPath = employee.ProfilePath;

            string password = employee.Password;
            string decrPassword = EncryptionUtil.MD5Decrypt(password, C_DecrKey.KEY_USER_PASSWORD);
            if (password == decrPassword)
            {
                Alert.ShowDialog(AlertType.Warning, "密码", "加载失败");
                this.txbPassword.Password = "";
            }
            else
            {
                this.txbPassword.Password = decrPassword;
            }

            this.cbbDept.SelectedValue = employee.DeptId;
            this.cbbArea.SelectedValue = employee.AreaId;
            this.cbbGroup.SelectedValue = employee.EmpGroupId;
            this.cbbDuty.SelectedValue = employee.DutyId;
            this.cbbComp.SelectedValue = employee.CompetenceId;
            this.cbbGender.SelectedValue = employee.GenderId;
            this.cbbIdentityType.SelectedValue = employee.IdentityTypeId;

            SetYesNoCombobox(cbbIsSpecialist, employee.IsSpecialist);
            SetYesNoCombobox(cbbIsNurse, employee.IsNurse);
            SetYesNoCombobox(cbbIsDoctor, employee.IsDoctor);

            bool defaultPic = true;
            if (!string.IsNullOrEmpty(m_photoPath))
            {
                string photoPath = Senvironments.BaseDirectory + m_photoPath;
                if (File.Exists(photoPath))
                {
                    SetImage(photoPath);
                    defaultPic = false;
                }
                else
                {
                    photoPath = DownloadPhoto(m_photoPath);
                    if (File.Exists(photoPath))
                    {
                        SetImage(photoPath);
                        defaultPic = false;
                    }
                }
            }

            if (defaultPic)
            {
                SetImage(Senvironments.BaseDirectory + DEFAULT_PHOTO_PATH);
            }
        }

        /// <summary>
        /// Set Image
        /// </summary>
        /// <param name="filePath"></param>
        private void SetImage(string filePath)
        {
            Stream stream = null;

            try
            {
                if (File.Exists(filePath))
                {
                    imgEmployee.Source = new BitmapImage(new Uri(filePath));
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                GCUtil.CloseStream(stream);
            }
        }

        /// <summary>
        /// Set Combobox
        /// </summary>
        /// <param name="combobox"></param>
        /// <param name="flag"></param>
        private void SetYesNoCombobox(ComboBox combobox, bool flag)
        {
            foreach (ComboBoxItem cbi in combobox.Items)
            {
                if (Convert.ToBoolean(cbi.Tag) == flag)
                {
                    combobox.SelectedItem = cbi;
                    break;
                }
            }
        }

        /// <summary>
        /// Check Data
        /// </summary>
        /// <returns></returns>
        protected override bool CheckData()
        {
            m_errors.Clear();

            string empName = txbEmpName.Text.Trim();
            string spellCode = txbSpellCode.Text.Trim();
            string systemName = txbSystemName.Text.Trim();
            string password = txbPassword.Password.Trim();
            string telephone = txbTelephone.Text.Trim();
            string mobilephone = txbMobilePhone.Text.Trim();
            string identity = txbIdentity.Text.Trim();
            string address = txbAddress.Text.Trim();
            string photoPath = m_photoPath;
            DateTime birthday = DateTime.Now;
            int deptId = -1;
            int areaId = -1;
            int groupId = -1;
            string duitId = "";
            string competenceId = "";
            string genderId = "";
            string identityType = "";
            bool isSpecial = Convert.ToBoolean(((ComboBoxItem)(cbbIsSpecialist.SelectedItem)).Tag);
            bool isDoctor = Convert.ToBoolean(((ComboBoxItem)(cbbIsDoctor.SelectedItem)).Tag);
            bool isNurse = Convert.ToBoolean(((ComboBoxItem)(cbbIsNurse.SelectedItem)).Tag);

            if (string.IsNullOrEmpty(empName))
            {
                m_errors.Add("姓名", "不能为空!");
            }
            if (string.IsNullOrEmpty(spellCode))
            {
                m_errors.Add("拼音码", "不能为空!");
            }
            if (string.IsNullOrEmpty(systemName))
            {
                m_errors.Add("系统用户名", "不能为空!");
            }
            if (string.IsNullOrEmpty(password))
            {
                m_errors.Add("系统密码", "不能为空!");
            }
            else
            {
                string enPassword = EncryptionUtil.MD5Encrypt(password, C_DecrKey.KEY_USER_PASSWORD);
                if (enPassword == password)
                {
                    m_errors.Add("系统密码", "加密失败!");
                }
                else
                {
                    password = enPassword;
                }
            }

            if (dtpBirthday.SelectedDate == null)
            {
                m_errors.Add("出生日期", "不能为空!");
            }
            else
            {
                birthday = (DateTime)dtpBirthday.SelectedDate;
            }

            if (string.IsNullOrEmpty(identity))
            {
                m_errors.Add("证件号码", "不能为空!");
            }
            if (cbbDept.SelectedValue == null)
            {
                m_errors.Add("所属科室", "不能为空!");
            }
            else
            {
                deptId = Convert.ToInt32(cbbDept.SelectedValue);
            }
            if (cbbArea.SelectedValue == null)
            {
                m_errors.Add("所属病区", "不能为空!");
            }
            else
            {
                areaId = Convert.ToInt32(cbbArea.SelectedValue);
            }
            if (cbbGroup.SelectedValue == null)
            {
                m_errors.Add("员工组", "不能为空!");
            }
            else
            {
                groupId = Convert.ToInt32(cbbGroup.SelectedValue);
            }
            if (cbbDuty.SelectedValue == null)
            {
                m_errors.Add("职务", "不能为空!");
            }
            else
            {
                duitId = cbbDuty.SelectedValue.ToString();
            }
            if (cbbComp.SelectedValue == null)
            {
                m_errors.Add("职位等级", "不能为空!");
            }
            else
            {
                competenceId = cbbComp.SelectedValue.ToString();
            }
            if (cbbGender.SelectedValue == null)
            {
                m_errors.Add("性别", "不能为空!");
            }
            else
            {
                genderId = cbbGender.SelectedValue.ToString();
            }
            if (cbbIdentityType.SelectedValue == null)
            {
                m_errors.Add("证件类别", "不能为空!");
            }
            else
            {
                identityType = cbbIdentityType.SelectedValue.ToString();
            }

            if (m_errors.Count == 0)
            {
                if (this.Crud == CrudType.Create)
                {
                    Employee = new M7_Employee();
                    Employee.HireDate = DateTime.Now;
                    Employee.LeaveDate = DateTime.Now;
                }
                Employee.FullName = empName;
                Employee.SpellCode = spellCode;
                Employee.Username = systemName;
                Employee.Password = password;
                Employee.Telephone = telephone;
                Employee.Mobilephone = mobilephone;
                Employee.IdentityId = identity;
                Employee.CurrentAddr = address;
                Employee.Birthday = birthday;
                Employee.IsDoctor = isDoctor;
                Employee.IsNurse = isNurse;
                Employee.IsSpecialist = isSpecial;
                Employee.DeptId = deptId;
                Employee.AreaId = areaId;
                Employee.EmpGroupId = groupId;
                Employee.GenderId = genderId;
                Employee.IdentityTypeId = identityType;
                Employee.DutyId = duitId;
                Employee.CompetenceId = competenceId;

                Employee.Department = m_deptList.Find(delegate(M7_Department __department)
                {
                    return __department.DeptId == deptId;
                });
                Employee.SickArea = m_areaList.Find(delegate(M7_SickArea __area)
                {
                    return __area.AreaId == areaId;
                });
                Employee.EmpGroup = m_groupList.Find(delegate(M7_EmployeeGroup __group)
                {
                    return __group.EmpGroupId == groupId;
                });
                Employee.Duty = m_dutyList.Find(delegate(M7_Duty __duty)
                {
                    return __duty.DutyId == duitId;
                });
                Employee.Competence = m_competenceList.Find(delegate(M7_Competence __competence)
                {
                    return __competence.CompetenceId == competenceId;
                });
                Employee.Gender = m_genderList.Find(delegate(M7_Gender __gender)
                {
                    return __gender.GenderId == genderId;
                });
                Employee.IdentityType = m_identityTypeList.Find(delegate(M7_IdentityType __identityType)
                {
                    return __identityType.IdentityTypeId == identityType;
                });
            }
            return base.CheckData();
        }

        /// <summary>
        /// Add Data
        /// </summary>
        protected override void AddData()
        {
            int result = -1;
            switch (m_crud)
            {
                case CrudType.Create:
                    {
                        S7_Citizen existCitizen = Agent_INFS.GetCitizenByIdentityId(Convert.ToInt32(Employee.IdentityTypeId), Employee.IdentityId);
                        if (existCitizen != null)
                        {
                            Alert.ShowDialog(AlertType.Error, "此证件已存在");
                            return;
                        }

                        string citizenId = Guid.NewGuid().ToString("N").ToUpper();
                        Employee.CitizenId = citizenId;

                        int empGroupId = Employee.EmpGroupId;
                        int deptId = Employee.DeptId;
                        int seed = Agent_SYSS.GetTernarySeed(C_M7_TableName.EMPLOYEE, empGroupId.ToString(), deptId.ToString());
                        Employee.EmpId = Convert.ToInt64(PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.EMPLOYEE, empGroupId, deptId, seed).ToString());

                        if (!string.IsNullOrEmpty(m_photoPath) && File.Exists(m_photoPath))
                        {
                            string returnPath = UploadPhoto(Employee.EmpId, m_photoPath);
                            if (!string.IsNullOrEmpty(returnPath))
                            {
                                //Employee.ProfilePath = returnPath;
                            }
                        }

                        S7_Citizen citizen = CreateCitizenObject(Employee);
                        citizen.CitizenId = citizenId;
                        result = Agent_INFS.AddCitizen(citizen);
                        if (result > 0)
                        {
                            result = Agent_INFS.AddEmployee(Employee);
                            if (result > 0)
                            {
                                m_empList.Add(Employee);
                                m_tempEmpList.Add(Employee);
                                dtgMain.Items.Refresh();
                                SelectEmployeeItem(Employee);

                                SwitchPropertiyGroupsEnabledState(false);
                                SwitchActionButtonsState(false);
                            }
                            else
                            {
                                Alert.ShowDialog(AlertType.Error, "添加员工信息失败");
                            }
                        }
                        else
                        {
                            Alert.ShowDialog(AlertType.Error, "添加个人信息失败");
                        }
                    }
                    break;
                case CrudType.Update:
                    {
                        //if (m_photoPath != Employee.ProfilePath)
                        //{
                        //    Employee.ProfilePath = m_photoPath;
                        //    if (!string.IsNullOrEmpty(m_photoPath) && File.Exists(m_photoPath))
                        //    {
                        //        string returnPath = UploadPhoto(Employee.EmpId, m_photoPath);
                        //        if (!string.IsNullOrEmpty(returnPath))
                        //        {
                        //            Employee.ProfilePath = returnPath;
                        //        }
                        //    }
                        //}

                        result = Agent_INFS.UpdateEmployee(Employee);

                        S7_Citizen citizen = CreateCitizenObject(Employee);
                        result = Agent_INFS.UpdateCitizen(citizen);

                        dtgMain.Items.Refresh();
                        SwitchPropertiyGroupsEnabledState(false);
                        SwitchActionButtonsState(false);
                    }
                    break;
                default:
                    break;
            }

            base.AddData();
        }

        /// <summary>
        /// 上传照片
        /// </summary>
        private string UploadPhoto(long empId, string photoPath)
        {
            return "";  //先不要此功能
            //string returnPath = "";
            //if (!string.IsNullOrEmpty(photoPath) && File.Exists(photoPath))
            //{
            //    using (FileStream fileStream = new FileStream(photoPath, FileMode.Open, FileAccess.Read))
            //    {
            //        TransferFileMessage tfm = new TransferFileMessage();
            //        tfm.File_Stream = fileStream;

            //        string ext = photoPath.Substring(photoPath.LastIndexOf("."));
            //        string fileName = empId + ext;
            //        tfm.File_Name = fileName;

            //        string savePhotoPath = Senvironments.BaseDirectory + C_PathName.EMPLOYEE_IMAGE_DIR + fileName;
            //        string relativePhotoPath = C_PathName.EMPLOYEE_IMAGE_DIR + fileName;
            //        string saveDir = savePhotoPath.Substring(0, savePhotoPath.LastIndexOf("\\"));
            //        if (!Directory.Exists(saveDir))
            //        {
            //            Directory.CreateDirectory(saveDir);
            //        }
            //        File.Copy(photoPath, savePhotoPath, true);

            //        var result = Agent_TRAS.UploadCitizenProfile("", relativePhotoPath);
            //        if (result.ErrorCode == 0)
            //        {
            //            returnPath = relativePhotoPath;
            //        }
            //        else
            //        {
            //            if (result.ErrorCode == -1)
            //            {
            //                Alert.ShowDialog(AlertType.Warning, "文件传输对象为空!");
            //            }
            //            else if (result.ErrorCode == -2)
            //            {
            //                Alert.ShowDialog(AlertType.Warning, "文件名为空!");
            //            }
            //            else if (result.ErrorCode == -3)
            //            {
            //                Alert.ShowDialog(AlertType.Warning, "文件流为空!");
            //            }
            //        }
            //    }
            //}
            //return returnPath;
        }

        /// <summary>
        /// 下载照片
        /// </summary>
        private string DownloadPhoto(string photoPath)
        {
            return "";  //下载时Service不能返回,  不知道为什么 ??  先不要此功能
            string returnPath = "";
            if (!string.IsNullOrEmpty(photoPath))
            {
                int result = Agent_TRAS.DownloadFile(photoPath);

                if (result == 0)
                {
                    returnPath = Senvironments.BaseDirectory + photoPath;
                }
            }

            return returnPath;
        }

        /// <summary>
        /// Create CitizenObject
        /// </summary>
        /// <param name="employee"></param>
        /// <returns></returns>
        private S7_Citizen CreateCitizenObject(M7_Employee employee)
        {
            S7_Citizen citizen = new S7_Citizen();

            PropertyInfo[] propertyArr = ReflectionUtil.GetProperties(citizen);

            foreach (PropertyInfo property in propertyArr)
            {
                string propertyName = property.Name;

                object propertyValue = ReflectionUtil.GetPropertyValue(employee, propertyName);
                ReflectionUtil.SetPropertyValue(citizen, propertyName, propertyValue);
            }

            citizen.CitizenId = employee.CitizenId;

            return citizen;
        }

        /// <summary>
        /// 选中Item
        /// </summary>
        /// <param name="employee"></param>
        private void SelectEmployeeItem(M7_Employee employee)
        {
            if (dtgMain.Items.Contains(employee))
            {
                dtgMain.SelectedItem = employee;
            }
        }

        /// <summary>
        /// 初始化窗口
        /// </summary>
        /// <param name="crud">窗口操作类型</param>
        public void InitializeControl(CrudType crud)
        {
            m_crud = crud;

            string prefix = string.Empty;
            switch (m_crud)
            {
                case CrudType.Create:
                    prefix = "新建";
                    InitializeForCreating();
                    break;
                case CrudType.Update:
                    prefix = "修改";
                    InitializeForUpdating();
                    break;
                default:
                    break;
            }

            InitializeForOthers();

            this.Tag = string.Format("{0}{1}", prefix, this.Tag);

            this.DataContext = m_entity;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            InitializeControl(CrudType.Create);
        }

        /// <summary>
        /// 初始化添加
        /// </summary>
        protected override void InitializeForCreating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ClearDepartmentPropertiye();

            base.InitializeForCreating();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Employee)
            {
                var employee = dtgMain.SelectedItem as M7_Employee;
                Employee = employee;
                InitializeControl(CrudType.Update);
            }
        }

        /// <summary>
        /// 初始化修改
        /// </summary>
        protected override void InitializeForUpdating()
        {
            SwitchPropertiyGroupsEnabledState(true);
            SwitchActionButtonsState(true);
            ShowEmployeeInfor(Employee);

            base.InitializeForUpdating();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dtgMain.SelectedItem is M7_Employee)
            {
                MessageBoxResult mbr = Alert.ShowDialog(AlertType.Question, "是否确定删除员工");
                if (mbr == MessageBoxResult.Yes)
                {
                    M7_Employee employee = dtgMain.SelectedItem as M7_Employee;
                    S7_Citizen citizen = CreateCitizenObject(employee);

                    int ret = Agent_INFS.DeleteCitizen(citizen.CitizenId);
                    if (ret > 0)
                    {
                        ret = Agent_INFS.DeleteEmployee(employee.EmpId);
                        if (ret > 0)
                        {
                            if (m_empList.Contains(employee))
                            {
                                int index = dtgMain.Items.IndexOf(employee);
                                index++;

                                m_empList.Remove(employee);
                                dtgMain.Items.Refresh();

                                if (dtgMain.Items.Count != 0)
                                {
                                    while (index >= dtgMain.Items.Count)
                                    {
                                        index--;
                                    }
                                    dtgMain.SelectedIndex = index;
                                }
                            }

                            if (m_tempEmpList.Contains(employee))
                            {
                                m_tempEmpList.Remove(employee);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 确定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (CheckData())
            {
                AddData();
            }
            else
            {
                ShowErrors();
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            SwitchPropertiyGroupsEnabledState(false);
            SwitchActionButtonsState(false);

            if (dtgMain.SelectedItem != null && dtgMain.SelectedItem is M7_Employee)
            {
                M7_Employee employee = dtgMain.SelectedItem as M7_Employee;
                ShowEmployeeInfor(employee);
            }

            m_crud = CrudType.Unknown;
        }

        /// <summary>
        ///  Search关键值改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsChanging(object sender, KeyEventArgs e)
        {
            string keywords = searchBox.Keywords;
            m_empList = m_tempEmpList.FindAll(delegate(M7_Employee __employee)
            {
                if (__employee.EmpId.ToString().Contains(keywords) ||
                    __employee.FullName.Contains(keywords) ||
                    __employee.Username.Contains(keywords))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
            ClientUtil.LoadItemsSource(dtgMain, m_empList);
        }

        /// <summary>
        /// Search关键值重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchBox_KeywordsReset(object sender, EventArgs e)
        {
            m_empList.Clear();
            m_empList.AddRange(m_tempEmpList.ToArray());

            ClientUtil.LoadItemsSource(dtgMain, m_empList);
        }

        /// <summary>
        /// Browse
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Multiselect = false;
            open.Title = "选择文件";
            open.Filter = "图片(*.png;*.jpg;*.jpeg'*.gif)|*.png;*.jpg;*.jpeg'*.gif";
            if ((bool)open.ShowDialog().GetValueOrDefault())
            {
                string fileName = open.FileName;
                if (File.Exists(fileName))
                {
                    SetImage(fileName);
                    m_photoPath = fileName;
                }
                else
                {
                    Alert.ShowDialog(AlertType.Warning, "图片不存在!");
                }
            }
        }

        /// <summary>
        /// Reset Image
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnResetImage_Click(object sender, RoutedEventArgs e)
        {
            SetImage(Senvironments.BaseDirectory + DEFAULT_PHOTO_PATH);
            m_photoPath = "";
        }

        ///// <summary>
        ///// MD5 加密
        ///// </summary>
        ///// <param name="strText"></param>
        ///// <param name="strEncrKey"></param>
        ///// <returns></returns>
        //private String MD5Encrypt(String strText, String strEncrKey)        
        //{            
        //    MemoryStream ms = null;
        //    CryptoStream cs = null;
        //    Byte[] byKey = {};            
        //    Byte[] IV = { 0x01, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        //    try
        //    {
        //        byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
        //        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        //        Byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
        //        ms = new MemoryStream();
        //        cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
        //        cs.Write(inputByteArray, 0, inputByteArray.Length);
        //        cs.FlushFinalBlock();
        //        return Convert.ToBase64String(ms.ToArray());
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.WriteLine(LogSeverityType.ERR, "EmployeeSummaryControl", ":MD5Encrypt {0}", ex);
        //    }
        //    finally
        //    {
        //        GCUtil.CloseStream(ms);
        //        GCUtil.CloseStream(cs);
        //    }
        //    return strText;
        //}       
        
        ///// <summary>
        ///// MD5 解密
        ///// </summary>
        ///// <param name="strText"></param>
        ///// <param name="sDecrKey"></param>
        ///// <returns></returns>
        //private String MD5Decrypt(String strText, String sDecrKey)  
        //{                     
        //    char[] stBase=strText.ToCharArray();   
        //    for (int i = 0; i < stBase.Length; i++)   
        //    {            
        //        if (stBase[i] ==' ')   
        //        {               
        //            stBase[i] = '+';    
        //        }         
        //    }          
        //    strText = "";   
        //    for (int i = 0; i < stBase.Length; i++) 
        //    {         
        //        strText += stBase[i];  
        //    }        
        //    Byte[] byKey  = {};   
        //    Byte[] IV = { 0x01,0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};   
        //    Byte[] inputByteArray = new byte[strText.Length];
        //    MemoryStream ms = null;
        //    CryptoStream cs = null;
        //    try          
        //    {           
        //        byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); 
        //        DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
        //        inputByteArray = Convert.FromBase64String(strText);     
        //        ms = new MemoryStream();        
        //        cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
        //        cs.Write(inputByteArray, 0, inputByteArray.Length);
        //        cs.FlushFinalBlock();             
        //        System.Text.Encoding encoding = System.Text.Encoding.UTF8;  
        //        return encoding.GetString(ms.ToArray());         
        //    }           
        //    catch(Exception ex)     
        //    {
        //        Log.WriteLine(LogSeverityType.ERR, "EmployeeSummaryControl", ":MD5Encrypt {0}", ex);  
        //    }
        //    finally
        //    {
        //        GCUtil.CloseStream(ms);
        //        GCUtil.CloseStream(cs);
        //    }
        //    return strText;
        //}
        #endregion

        #region Structure

        /// <summary>
        /// 构造方法
        /// </summary>
        public EmployeeSummaryControl()
        {
            InitializeComponent();
        }

        #endregion

        #region Inner members

        /// <summary>
        /// 员工信息列表
        /// </summary>
        private List<M7_Employee> m_empList;

        /// <summary>
        /// 员工信息临时列表
        /// </summary>
        private List<M7_Employee> m_tempEmpList = new List<M7_Employee>();

        /// <summary>
        /// 员工组信息列表
        /// </summary>
        private List<M7_EmployeeGroup> m_groupList;

        /// <summary>
        /// 科室信息列表
        /// </summary>
        private List<M7_Department> m_deptList;

        /// <summary>
        /// 病区信息列表
        /// </summary>
        private List<M7_SickArea> m_areaList;

        /// <summary>
        /// 职务信息列表
        /// </summary>
        private List<M7_Duty> m_dutyList;

        /// <summary>
        /// 职位等级信息列表
        /// </summary>
        private List<M7_Competence> m_competenceList;

        /// <summary>
        /// 性别信息列表
        /// </summary>
        private List<M7_Gender> m_genderList;

        /// <summary>
        /// 证件类型信息列表
        /// </summary>
        private List<M7_IdentityType> m_identityTypeList;

        /// <summary>
        /// Photo Path
        /// </summary>
        private string m_photoPath = "";

        /// <summary>
        /// Default Photo Path
        /// </summary>
        private const string DEFAULT_PHOTO_PATH = C_PathName.EMPLOYEE_IMAGE_DIR + "default_avatar.png";
        #endregion
    }
}
